// 获取应用实例
const app = getApp()
const api = app.globalData.api

Page({
    data: {
        info: [],
        detail: {},
        isTaxOption: [],
        kehuOption: [],
        typeOption: [],
        deliveryMethodOption: [],
        settlementTypeOption: [],
        deliveryMethod: '',
        khid: '',
        isTaxText: '否',
        calendar: false,
        nowDate: new Date().getTime(),
        orderDate: '',
        total: 0,
        count: 0,
        dateField: '',
        typePopup: false,
        kehuPopup: false,
        isTaxPopup: false
    },
    // 获取客户
    getKehu: async function () {
        let res = await api.curlGet('?cla=inventoryOther&fun=kehu')
        if (res.code === 1) {
            this.setData({
                kehuOption: res.data
            })
        }
    },

    // 编辑选项
    editOption: async function () {
      let res = await api.curlGet('?cla=saleSendOrder&fun=editOption')
      if (res.code === 1) {
          let isTax = this.data.info.isTax ? this.data.info.isTax : '0'
          this.setData({
            deliveryMethodOption: res.data.deliveryMethod,
            isTaxOption: res.data.isTax,
            settlementTypeOption: res.data.settlement,
            deliveryMethod: this.findTextByValue(res.data.deliveryMethod,this.data.info.delivery_method),
            isTaxText: this.findTextByValue(res.data.isTax,isTax),
            ['info.isTax']: isTax
          })
      }
    },
    // 获取选项
    getSearch: async function () {
        let res = await api.curlGet('?cla=saleSendOrder&fun=search')
        if (res.code === 1) {
            this.setData({
                typeOption: res.data.search.type.array
            })
        }
    },
    main: async function () {
        await this.getKehu()
        await this.editOption()
        await this.getSearch()
    },
    // 更新本地数据
    syncStorage: async function (id) {
        let that = this,
            saleData = {}
        let res = await api.curlPost('?cla=saleSendOrder&fun=detail', {id: id})
        if (res.code === 1) {
            let result = res.data.result.detail
            for (const index in result) {
                saleData[result[index]['materialId']] = result[index]
            }
            wx.setStorageSync('saleInfo', res.data.result.info)
            wx.setStorageSync('saleData', saleData)
            that.setData({
                total: api.total(saleData, 'total'),
                count: api.count(saleData),
                info: res.data.result.info,
                detail: saleData
            })
        }
    },
    onLoad: async function (options) {
        let that = this,
            id = options.id ? options.id : ''
        if (id) {
            await that.syncStorage(id)
        }else{
            wx.removeStorageSync('saleInfo')
            wx.removeStorageSync('saleData')
        }
        await that.main()
    },
    // 刷新物料信息
    onShow: async function () {
        const that = this
        const saleData = wx.getStorageSync('saleData')
        // console.log(saleData)
        that.setData({
            total: api.total(saleData, 'total'),
            count: api.count(saleData),
            detail: saleData
        })
    },
    onDisplay: function (e) {
        let obj = e.currentTarget.dataset
        this.setData({
            calendar: true,
            dateField: obj.field
        })
    },
    // 关闭
    onClose: function (e) {
        let obj = e.currentTarget.dataset
        if (obj) {
            this.setData({[obj.target]: false})
        }
    },
    goto(e) {
        return api.goto(e)
    },
    findTextByValue(data,valueToFind) {
      let foundObject = data.find(item => item.value === valueToFind);  
      return foundObject ? foundObject.text : null; 
    },
    funRouting(type, detail) {
        switch (type) {
            case 'recordDate':
            case 'deliveryDate':
                return api.formatDate(detail)
            case 'type':
            case 'settlementType':
                return detail.value
            case 'delivery_method':
                this.setData({
                  deliveryMethod: detail.value.text
                })
                return detail.value.value
            case 'isTax':
                this.setData({
                  isTaxText: detail.value.text
                })
                return detail.value.value
            case 'target':
                const array = detail.value
                this.setData({
                    ['info.targetId']: array['value']
                })
                return array['text']
        }
    },
    // 确认选择
    onConfirm: function (e) {
        let obj = e.currentTarget.dataset
        let field = 'info.' + obj.field
        this.setData({
            [obj.target]: false,
            [field]: this.funRouting(obj.field, e.detail),
        })
        // console.log(this.data.info)
    },
    showPopup: function (obj) {
        let popup = obj.currentTarget.dataset.show
        if (popup) {
            this.setData({
                [popup]: true
            });
        }
    },
    onDelete(obj) {
        const id = obj.currentTarget.dataset.id
        const {position, instance} = obj.detail;
        const saleData = wx.getStorageSync('saleData')
        switch (position) {
            // case 'left':
            // case 'cell':
            //     instance.close();
            //     break;
            case 'right':
                wx.showModal({
                    title: '提示',
                    content: '确定删除吗？',
                    success: (res) => {
                        if (res.confirm) {
                            delete saleData[id]
                            wx.setStorageSync('saleData', saleData)
                            instance.close()
                            this.setData({detail: saleData})
                            api.showToast('删除成功')
                        }
                    },
                })
                break;
        }
    },
    formSubmit: async function (e) {
        let obj = e.detail.value
        let saleData = wx.getStorageSync('saleData')
        let saleDataArray = Object.values(saleData)
        saleDataArray.forEach(function (item) {
            item['mxText'] = item['text']
            delete item['text']
        })
        obj['detail'] = api.arrayToJson(saleDataArray)
        if (obj) {
            let res = await api.curlPost('?cla=saleSendOrder&fun=edit', obj)
            if (res.code === 1) {
                wx.navigateTo({
                    url: 'detail?id=' + res.data
                })
                wx.removeStorageSync('saleData')
                api.showToast('新增成功', 'success')
            } else {
                api.showToast(res.warn)
            }
        }
    }
});